//
//  GRChooseLocationViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/16.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRChooseLocationViewController.h"
#import "GRLocationTitleView.h"
#import "GRMyAddressTableViewCell.h"
@interface GRChooseLocationViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet GRLocationTitleView *titleContentView;
@property (weak, nonatomic) IBOutlet UIScrollView *mainContentView;
@property(nonatomic,strong)UIView * underLine;
@property(nonatomic,weak)UIButton * selectedBtn;
@property (nonatomic,strong) NSMutableArray * ProvinceDataArr;
@property (nonatomic,strong) NSMutableArray * cityDataArr;
@property (nonatomic,strong) NSMutableArray * districtDataArr;
@property (nonatomic,strong) NSMutableArray * tableViews;
@property (nonatomic,strong) NSMutableArray * topTabbarItems;
@property (nonatomic,strong)NSIndexPath * firstSelectIndex;
@property (nonatomic,strong)NSIndexPath *secondtSelectIndex;
@property(nonatomic,strong)NSIndexPath * thirdIndex;


@end

@implementation GRChooseLocationViewController
- (NSMutableArray *)tableViews{
    
    if (_tableViews == nil) {
        _tableViews = [NSMutableArray array];
    }
    return _tableViews;
}

- (NSMutableArray *)topTabbarItems{
    if (_topTabbarItems == nil) {
        _topTabbarItems = [NSMutableArray array];
    }
    return _topTabbarItems;
}


-(void)showInContoller:(UIViewController *__weak)showVC {
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.view];
    self.view.frame = window.bounds;
    [showVC addChildViewController:self];
}

-(void)hiddenLocationView{
    
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self requestAddress:1 ParentID:0 SuccessBlock:^(NSMutableArray *addrssArr) {
        self.ProvinceDataArr = addrssArr;
        [self setUI];
    }];
 

}

-(void)requestAddress:(NSInteger)type ParentID:(NSInteger)parentID  SuccessBlock:(void(^)(NSMutableArray *addrssArr))successBlock{
    [RequestManager getAddressWithType:type ParentID:parentID ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        NSMutableArray * addressArr = [NSMutableArray array];
        if (Array(responseObject)) {
            for (NSDictionary * dic in responseObject) {
                GRMyAddressModel * addressModel = [GRMyAddressModel yy_modelWithDictionary:dic];
                [addressArr addObject:addressModel];
            }
        }
        successBlock(addressArr);
  
    }];
    
}

-(void)setUI{
    [self addTopBarItem];
    [_titleContentView layoutIfNeeded];
    UIView * underLine = [[UIView alloc] initWithFrame:CGRectZero];
    [_titleContentView addSubview:underLine];
    _underLine = underLine;
    underLine.height = 2.0f;
    underLine.top = _titleContentView.height - underLine.height-1;
    UIButton * btn = self.topTabbarItems.lastObject;
    [self changeUnderLineFrame:btn];

    _underLine.backgroundColor = KGMTHEM_COLOR;
    self.mainContentView.contentSize = CGSizeMake(KscreenWidth, 0);
    [self addTableView];
    self.mainContentView.delegate = self;
}

- (void)addTableView{
    UITableView * tabbleView = [[UITableView alloc]initWithFrame:CGRectMake(self.tableViews.count * KscreenWidth, 0, KscreenWidth, _mainContentView.bounds.size.height)];

    [_mainContentView addSubview:tabbleView];
    [self.tableViews addObject:tabbleView];
    tabbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tabbleView.delegate = self;
    tabbleView.dataSource = self;
    [tabbleView registerNib:[UINib nibWithNibName:@"GRMyAddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"addressCell"];
}


- (void)addTopBarItem{
    
    UIButton * topBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    [topBarItem setTitle:@"请选择" forState:UIControlStateNormal];
    [topBarItem setTitleColor:HEXCOLOR(0x222222) forState:UIControlStateNormal];

    [topBarItem sizeToFit];
    topBarItem.centerY = _titleContentView.height * 0.5;
    [self.topTabbarItems addObject:topBarItem];
    [_titleContentView addSubview:topBarItem];
    [topBarItem addTarget:self action:@selector(topBarItemClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GRMyAddressTableViewCell * addressCell = [tableView dequeueReusableCellWithIdentifier:@"addressCell" forIndexPath:indexPath];
   GRMyAddressModel * addressModel;
    //省级别
    if([self.tableViews indexOfObject:tableView] == 0){
        addressModel = self.ProvinceDataArr[indexPath.row];
        //市级别
    }else if ([self.tableViews indexOfObject:tableView] == 1){
       addressModel = self.cityDataArr[indexPath.row];
        //县级别
    }else if ([self.tableViews indexOfObject:tableView] == 2){
        addressModel = self.districtDataArr[indexPath.row];
    }
    addressCell.nameLabel.text = addressModel.name;
    return addressCell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if([self.tableViews indexOfObject:tableView] == 0){
        return self.ProvinceDataArr.count;
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        return self.cityDataArr.count;
    }else{
        return self.districtDataArr.count;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
       WEAKSELF
    if([self.tableViews indexOfObject:tableView] == 0){
        
        //1.1 获取下一级别的数据源(市级别,如果是直辖市时,下级则为区级别)
        GRMyAddressModel * provinceItem = self.ProvinceDataArr[indexPath.row];
     
        [self requestAddress:2 ParentID: provinceItem.id SuccessBlock:^(NSMutableArray *addrssArr) {
            weakSelf.cityDataArr = addrssArr;
            if(weakSelf.cityDataArr.count == 0){
                for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                    [weakSelf removeLastItem];
                }
                  _secondtSelectIndex = nil;
                _thirdIndex = nil;
                _firstSelectIndex = indexPath;
                [weakSelf setUpAddress:provinceItem.name];
            }else{
            if ([_firstSelectIndex compare:indexPath] != NSOrderedSame && _firstSelectIndex) {
                for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                    [weakSelf removeLastItem];
                }
                _secondtSelectIndex = nil;
                _thirdIndex = nil;
                  _firstSelectIndex  = indexPath;
                [weakSelf addTopBarItem];
                [weakSelf addTableView];
                [weakSelf scrollToNextItem:provinceItem.name];
              }else if ([_firstSelectIndex compare:indexPath] == NSOrderedSame && _firstSelectIndex){
                [self scrollToNextItem:provinceItem.name];
              }else{
                  [weakSelf addTopBarItem];
                  [weakSelf addTableView];
                  [weakSelf scrollToNextItem:provinceItem.name];
                  _firstSelectIndex  = indexPath;
              }
            }
            }];
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        GRMyAddressModel * cityItem = self.cityDataArr[indexPath.row];
        [self requestAddress:3 ParentID:cityItem.id SuccessBlock:^(NSMutableArray *addrssArr) {
            self.districtDataArr = addrssArr;
            if(addrssArr.count == 0){
            for (int i = 0; i < self.tableViews.count - 1&&self.tableViews.count != 2; i++) {
                    [self removeLastItem];
                }
                     _thirdIndex = nil;
                 _secondtSelectIndex  = indexPath;
                [weakSelf setUpAddress:cityItem.name];
            }else{
                    if ([_secondtSelectIndex compare:indexPath] != NSOrderedSame && _secondtSelectIndex) {
                
                        for (int i = 0; i < self.tableViews.count - 1&&self.tableViews.count != 2; i++) {
                               [self removeLastItem];
                               }
                  _thirdIndex = nil;
                [self addTopBarItem];
                [self addTableView];
                [self scrollToNextItem:cityItem.name];
                _secondtSelectIndex = indexPath;
            }else if ([_secondtSelectIndex compare:indexPath] == NSOrderedSame && _secondtSelectIndex){
                [self scrollToNextItem:cityItem.name];
            }else{
                [self addTopBarItem];
                [self addTableView];
                [self scrollToNextItem:cityItem.name];
                  _secondtSelectIndex = indexPath;
                }
            }
        }];
    }else if ([self.tableViews indexOfObject:tableView] == 2){
         _thirdIndex = indexPath;
        GRMyAddressModel * item = self.districtDataArr[indexPath.row];
        [self setUpAddress:item.name];
       
    }

}
         
- (void)setUpAddress:(NSString *)address{
    NSInteger index = self.mainContentView.contentOffset.x / KscreenWidth;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:address forState:UIControlStateNormal];
    [btn sizeToFit];
    [_titleContentView layoutIfNeeded];
    [self changeUnderLineFrame:btn];
   GRMyAddressModel * provinceModel;
    GRMyAddressModel * cityModel;
    GRMyAddressModel * areaModel;
    if (_firstSelectIndex) {
        provinceModel = self.ProvinceDataArr[_firstSelectIndex.row];
    }
    if (_secondtSelectIndex) {
        cityModel = self.cityDataArr[_secondtSelectIndex.row];
    }
    if (_thirdIndex) {
        areaModel = self.districtDataArr[_thirdIndex.row];
    }
    if (self.chooseFinish != nil) {
        self.chooseFinish(provinceModel, cityModel, areaModel);
    }
    [self hiddenLocationView];
    
}


- (void)removeLastItem{
    [self.tableViews.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.tableViews removeLastObject];
    
    [self.topTabbarItems.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.topTabbarItems removeLastObject];
}


//滚动到下级界面,并重新设置顶部按钮条上对应按钮的title
- (void)scrollToNextItem:(NSString *)preTitle{
    NSInteger index = self.mainContentView.contentOffset.x / KscreenWidth;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:preTitle forState:UIControlStateNormal];
    [btn sizeToFit];
    [_titleContentView layoutIfNeeded];
    [UIView animateWithDuration:0.25 animations:^{
        self.mainContentView.contentSize = (CGSize){self.tableViews.count * KscreenWidth,0};
        CGPoint offset = self.mainContentView.contentOffset;
        self.mainContentView.contentOffset = CGPointMake(offset.x + KscreenWidth, offset.y);
        [self changeUnderLineFrame: [self.titleContentView.subviews lastObject]];
    }];
}

#pragma mark - <UIScrollView>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView != self.mainContentView) return;
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        NSInteger index = scrollView.contentOffset.x / KscreenWidth;
        UIButton * btn = weakSelf.topTabbarItems[index];
        [weakSelf changeUnderLineFrame:btn];
    }];
}

#pragma mark - private

//点击按钮,滚动到对应位置
- (void)topBarItemClick:(UIButton *)btn{
    
    NSInteger index = [self.topTabbarItems indexOfObject:btn];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.mainContentView.contentOffset = CGPointMake(index *KscreenWidth, 0);
        [self changeUnderLineFrame:btn];
    }];
}

//调整指示条位置
- (void)changeUnderLineFrame:(UIButton  *)btn{
    _underLine.left = btn.left;
    _underLine.width = btn.width;
}


- (IBAction)closeAction:(id)sender {
    [self hiddenLocationView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
